﻿using Newtonsoft.Json.Linq;
using LibreHardwareMonitor.Hardware;
using System;
using System.IO;
using System.Threading;

namespace cpu_temp
{

    public class UpdateVisitor : IVisitor
    {
        public void VisitComputer(IComputer computer)
        {
            computer.Traverse(this);
        }
        public void VisitHardware(IHardware hardware)
        {
            hardware.Update();
            foreach (IHardware subHardware in hardware.SubHardware) subHardware.Accept(this);
        }
        public void VisitSensor(ISensor sensor) { }
        public void VisitParameter(IParameter parameter) { }
    }

    
    class Program
    {
        static void Main()
        {
            // 实例化硬件类
            Computer myComputer = new Computer
            {
                IsCpuEnabled = true,
                IsGpuEnabled = true,
                IsMemoryEnabled = true,
                IsMotherboardEnabled = true,
                IsControllerEnabled = true,
                IsNetworkEnabled = true,
                IsStorageEnabled = true
            };

            // 有时候实例化硬件会出错，尝试10次
            for (int i = 1; i <= 10; i++)
            {
                try
                {
                    myComputer.Open();
                    myComputer.Accept(new UpdateVisitor());
                }
                catch
                {
                    if (i == 10)
                    {
                        return;
                    }
                    System.Threading.Thread.Sleep(1500);
                    continue;
                }
            }

            // 传输的JSON初始化
            string json_data = @"{
                'CPU':{'Temperature':'','Name':''},
                'GPU':{'Temperature':'','Name':''},
                'SSD-1':{'Temperature':'','Name':''},
                'SSD-2':{'Temperature':'','Name':''},
                'SSD-3':{'Temperature':'','Name':''},
                'SSD-4':{'Temperature':'','Name':''},
                'SSD-5':{'Temperature':'','Name':''},
                'SSD-6':{'Temperature':'','Name':''}
            }";
            JObject HardWare_info = JObject.Parse(json_data);
            int ssd_count = 1; // 发现的硬盘数量

            string fan_speed = "";
            foreach (var hardwareItem in myComputer.Hardware)
            {
                // 提取风扇信息
                // Console.WriteLine(hardwareItem.HardwareType + "型号是：" + hardwareItem.Name);
                // 从主板上获取南桥芯片信息，然后根据南桥下面的Fan类型（要注意区分CPU风扇和系统风扇）
                // 南桥芯片信息
                if (hardwareItem.HardwareType == HardwareType.Motherboard)
                {
                    JObject cpu_fan = new JObject();
                    foreach (var Norbrige in hardwareItem.SubHardware)
                    {
                        foreach (var fan_sensor in Norbrige.Sensors)
                        {
                            // 风扇字段，不同的主板，显示不一样
                            // 先从大类开始找，转速大于0的，都记录下来
                            var tmp_str = fan_sensor.SensorType.ToString();
                            if (tmp_str == "Fan")
                            {
                                // 明确有CPU风扇字段的
                                if (fan_sensor.Name == "CPU Fan" && fan_sensor.Value > 0)
                                {
                                    // Console.WriteLine("CPU 风扇转速：" + fan_sensor.Value);
                                    fan_speed = fan_sensor.Value.ToString();
                                    break;
                                }
                                else if (fan_sensor.Value > 0)
                                {
                                    // Console.WriteLine("CPU 风扇转速：" + fan_sensor.Value);
                                    fan_speed = fan_sensor.Value.ToString();
                                }
                                else
                                {
                                    // Console.WriteLine("没有读取到风扇转速或者转速为0");
                                    fan_speed = "";
                                }
                            }
                        }
                        cpu_fan.Add(hardwareItem.HardwareType.ToString(), fan_speed);
                        // result.Add(cpu_fan);
                    }
                }
                // 非主板类硬件
                // 查找温度信息
                else
                {
                    foreach (var sensor in hardwareItem.Sensors)
                    {                        
                        // 类型是温度
                        if (sensor.SensorType == SensorType.Temperature)
                        {
                            string tmp_string = sensor.Name.ToString();
                            // CPU温度
                            if (hardwareItem.HardwareType == HardwareType.Cpu && tmp_string.Contains(" Max"))
                            {
                                HardWare_info["CPU"]["Temperature"] = sensor.Value.ToString();
                                HardWare_info["CPU"]["Name"] = hardwareItem.Name.ToString();
                            }
                            //显卡温度
                            else if (hardwareItem.HardwareType == HardwareType.GpuAmd || hardwareItem.HardwareType == HardwareType.GpuIntel || hardwareItem.HardwareType == HardwareType.GpuNvidia)
                            {
                                if (sensor.Name == "GPU Core")
                                {
                                    HardWare_info["GPU"]["Temperature"] = sensor.Value.ToString();
                                    HardWare_info["GPU"]["Name"] = hardwareItem.Name.ToString();
                                }
                            }
                            // 硬盘温度
                            else if (hardwareItem.HardwareType == HardwareType.Storage && sensor.Name == "Temperature")
                            {
                                HardWare_info["SSD-" + ssd_count]["Temperature"] = sensor.Value.ToString();
                                HardWare_info["SSD-" + ssd_count]["Name"] = hardwareItem.Name.ToString();
                                ssd_count++;
                            }
                        }
                    }
                }

            }
            myComputer.Close();
            Console.Write(HardWare_info.ToString());
            // System.Threading.Thread.Sleep(5000);
        }
    }//end main
}
